package com.sq.universe.system.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sq.universe.base.controller.BaseController;
import com.sq.universe.base.entity.RespEntity;
import com.sq.universe.base.utils.AuthUtils;
import com.sq.universe.base.utils.MD5Utils;
import com.sq.universe.system.entity.UserEntity;
import com.sq.universe.system.service.UserRoleService;
import com.sq.universe.system.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController extends BaseController {

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private UserService userService;

    /**
     * 查询数据
     * @param userEntity
     * @return
     */
    @PostMapping("/query")
    @RequiresPermissions("system:user:query")
    public RespEntity query(@RequestBody(required = false) UserEntity userEntity){
        try {
            return new RespEntity("查询成功",userService.query(userEntity));
        }catch (Exception exception){
            return new RespEntity("查询失败");
        }
    }

    /**
     * 分页查询
     * @param userEntity
     * @return
     */
    @PostMapping("/queryByPage")
    @RequiresPermissions("system:user:queryByPage")
    public RespEntity queryByPage(@RequestBody(required = false) UserEntity userEntity){
        try {
            PageHelper.startPage(userEntity.getPageNo(),userEntity.getPageSize());
            List<UserEntity> userList = userService.query(userEntity);
            PageInfo<UserEntity> pageInfo = new PageInfo<UserEntity>(userList);
            return new RespEntity("查询成功",pageInfo);
        }catch (Exception exception){
            return new RespEntity("查询失败");
        }
    }

    /**
     * 插入
     * @param userEntity
     * @return
     */
    @PostMapping("/insert")
    @RequiresPermissions("system:user:insert")
    public RespEntity insert(@RequestBody(required = false) UserEntity userEntity){
        try {
            userEntity.setUserCreateUser(getCurrentUser().getUserId());
            userEntity.setUserCreateTime(new Date());
            String passtord = MD5Utils.stringToMD5(userEntity.getUserPassword(),userEntity.getUserLoginName());
            userEntity.setUserPassword(passtord);
            userService.insert(userEntity);
            return new RespEntity("保存成功");
        }catch (Exception exception){
            return new RespEntity("保存失败");
        }
    }

    /**
     * 修改密码
     * @param user
     * @return
     */
    @PostMapping("/changePassword")
    public RespEntity changePassword(@RequestBody(required = false) Map<String,String> user){
        try {
            UserEntity currentUser = AuthUtils.getCurrentUser();
            String password = user.get("password");
            String oldPassword = user.get("oldPassword");
            String oldPasswordMd5 = MD5Utils.stringToMD5(oldPassword,currentUser.getUserLoginName());
            if(!oldPasswordMd5.equals(currentUser.getUserPassword())){
                return new RespEntity("密码错误",500);
            }
            UserEntity updateUser = new UserEntity();
            password = MD5Utils.stringToMD5(password,currentUser.getUserLoginName());
            updateUser.setUserPassword(password);
            updateUser.setUserId(currentUser.getUserId());
            userService.updateUserInfo(updateUser);
            return new RespEntity("保存成功");
        }catch (Exception exception){
            return new RespEntity("保存失败");
        }
    }


    /**
     * 更新
     * @param userEntity
     * @return
     */
    @PostMapping("/update")
    @RequiresPermissions("system:user:update")
    public RespEntity update(@RequestBody(required = false) UserEntity userEntity){
        try {
            userEntity.setUserUpdateUser(getCurrentUser().getUserId());
            userEntity.setUserUpdateTime(new Date());
            userEntity.setUserPassword(null);
            userService.update(userEntity);
            return new RespEntity("更新成功");
        }catch (Exception exception){
            return new RespEntity("更新失败");
        }
    }

    /**
     * 删除成功
     * @param userEntity
     * @return
     */
    @PostMapping("/delete")
    @RequiresPermissions("system:user:delete")
    public RespEntity delete(@RequestBody(required = false) UserEntity userEntity){
        try {
            if(userEntity.getUserId() == null){
                return new RespEntity("删除失败");
            }
            userEntity.setUserUpdateUser(getCurrentUser().getUserId());
            userEntity.setUserUpdateTime(new Date());
            userService.logicalDelete(userEntity);
            return new RespEntity("删除成功");
        }catch (Exception exception){
            return new RespEntity("删除失败");
        }
    }

    /**
     * 登录数据
     * @param userEntity
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public RespEntity login(@RequestBody(required = false) UserEntity userEntity){
        // 获取Subject实例对象，用户实例
        Subject currentUser = SecurityUtils.getSubject();
        Map map = new HashMap();

        map.put("token",SecurityUtils.getSubject().getSession().getId());
        UsernamePasswordToken token = new UsernamePasswordToken(userEntity.getUserLoginName(),userEntity.getUserPassword());
        currentUser.login(token);
        return new RespEntity("登陆成功",map);
    }


    @PostMapping("/logout")
    @ResponseBody
    public RespEntity logout(){
        try{
            Subject currentUser = SecurityUtils.getSubject();
            currentUser.logout();
        }catch (Exception e){
            e.printStackTrace();
        }
        return new RespEntity("退出成功");
    }

    @PostMapping("/info")
    @ResponseBody
    public RespEntity info(){
        UserEntity userInfo = null;
        try{
            userInfo = getCurrentUser();
        }catch (Exception e){
            e.printStackTrace();
        }
        return new RespEntity("获取用户信息成功",userInfo);
    }

    /**
     * 获取菜单列表
     * @return
     */
    @PostMapping("/getAuth")
    @ResponseBody
    public RespEntity getAuth(){
        try {
            return new RespEntity("获取菜单成功",userService.getAuth(getCurrentUser()));
        }catch (Exception e){
             e.printStackTrace();
            return new RespEntity("获取菜单失败");
        }
    }

    @PostMapping("/wxLogin")
    @ResponseBody
    public RespEntity wxLogin(){
        try {
            return new RespEntity("获取菜单成功",userService.getAuth(getCurrentUser()));
        }catch (Exception e){
            e.printStackTrace();
            return new RespEntity("获取菜单失败");
        }
    }

}
